import React, { useState, useEffect } from 'react';
import { Radio, Button, Modal, Input, Form, message, Space, Tooltip, Tag } from 'antd';
import {
  BulbOutlined,
  BalanceOutlined,
  AimOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SaveOutlined
} from '@ant-design/icons';
import { PARAMETER_PRESETS, ParameterPreset, ModelParameters } from '@/types/models';
import './style.css';

interface PresetSelectorProps {
  value?: string;
  onChange?: (presetId: string, preset: ParameterPreset) => void;
  onParametersChange?: (params: ModelParameters) => void;
  disabled?: boolean;
}

const PRESET_ICONS: Record<string, React.ReactNode> = {
  creative: <BulbOutlined />,
  balanced: <BalanceOutlined />,
  precise: <AimOutlined />
};

const PresetSelector: React.FC<PresetSelectorProps> = ({
  value = 'balanced',
  onChange,
  onParametersChange,
  disabled = false
}) => {
  const [presets, setPresets] = useState<Record<string, ParameterPreset>>(PARAMETER_PRESETS);
  const [selectedPreset, setSelectedPreset] = useState<string>(value);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingPreset, setEditingPreset] = useState<ParameterPreset | null>(null);
  const [form] = Form.useForm();

  // Load custom presets from localStorage
  useEffect(() => {
    const savedPresets = localStorage.getItem('customPresets');
    if (savedPresets) {
      try {
        const customPresets = JSON.parse(savedPresets);
        setPresets({ ...PARAMETER_PRESETS, ...customPresets });
      } catch (error) {
        console.error('Failed to load custom presets:', error);
      }
    }
  }, []);

  // Save custom presets to localStorage
  const saveCustomPresets = (updatedPresets: Record<string, ParameterPreset>) => {
    const customPresets: Record<string, ParameterPreset> = {};
    Object.entries(updatedPresets).forEach(([key, preset]) => {
      if (preset.isCustom) {
        customPresets[key] = preset;
      }
    });
    localStorage.setItem('customPresets', JSON.stringify(customPresets));
  };

  const handlePresetChange = (presetId: string) => {
    setSelectedPreset(presetId);
    const preset = presets[presetId];
    if (preset) {
      if (onChange) {
        onChange(presetId, preset);
      }
      if (onParametersChange) {
        onParametersChange(preset.parameters);
      }
    }
  };

  const handleCreatePreset = () => {
    setEditingPreset(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleEditPreset = (preset: ParameterPreset) => {
    setEditingPreset(preset);
    form.setFieldsValue({
      name: preset.name,
      description: preset.description,
      ...preset.parameters
    });
    setIsModalVisible(true);
  };

  const handleDeletePreset = (presetId: string) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除预设 "${presets[presetId].name}" 吗？`,
      onOk: () => {
        const updatedPresets = { ...presets };
        delete updatedPresets[presetId];
        setPresets(updatedPresets);
        saveCustomPresets(updatedPresets);
        
        if (selectedPreset === presetId) {
          handlePresetChange('balanced');
        }
        
        message.success('预设已删除');
      }
    });
  };

  const handleSavePreset = async () => {
    try {
      const values = await form.validateFields();
      const presetId = editingPreset?.id || `custom_${Date.now()}`;
      
      const newPreset: ParameterPreset = {
        id: presetId,
        name: values.name,
        description: values.description,
        parameters: {
          temperature: values.temperature,
          topP: values.topP,
          maxTokens: values.maxTokens,
          presencePenalty: values.presencePenalty || 0,
          frequencyPenalty: values.frequencyPenalty || 0
        },
        isCustom: true
      };
      
      const updatedPresets = { ...presets, [presetId]: newPreset };
      setPresets(updatedPresets);
      saveCustomPresets(updatedPresets);
      
      setIsModalVisible(false);
      message.success(editingPreset ? '预设已更新' : '预设已创建');
      
      // Auto-select the new/edited preset
      handlePresetChange(presetId);
    } catch (error) {
      message.error('请填写所有必填字段');
    }
  };

  return (
    <div className="preset-selector">
      <div className="preset-header">
        <span className="preset-title">参数预设</span>
        <Button
          type="link"
          icon={<PlusOutlined />}
          onClick={handleCreatePreset}
          disabled={disabled}
        >
          自定义
        </Button>
      </div>
      
      <Radio.Group
        value={selectedPreset}
        onChange={(e) => handlePresetChange(e.target.value)}
        disabled={disabled}
        className="preset-radio-group"
      >
        <Space direction="vertical" style={{ width: '100%' }}>
          {Object.values(presets).map(preset => (
            <Radio key={preset.id} value={preset.id} className="preset-radio">
              <div className="preset-option">
                <Space>
                  {PRESET_ICONS[preset.id] || <SaveOutlined />}
                  <span className="preset-name">{preset.name}</span>
                  {preset.isCustom && <Tag color="blue">自定义</Tag>}
                </Space>
                <div className="preset-description">{preset.description}</div>
                {preset.isCustom && (
                  <Space className="preset-actions">
                    <Tooltip title="编辑">
                      <Button
                        type="text"
                        size="small"
                        icon={<EditOutlined />}
                        onClick={(e) => {
                          e.stopPropagation();
                          handleEditPreset(preset);
                        }}
                      />
                    </Tooltip>
                    <Tooltip title="删除">
                      <Button
                        type="text"
                        size="small"
                        danger
                        icon={<DeleteOutlined />}
                        onClick={(e) => {
                          e.stopPropagation();
                          handleDeletePreset(preset.id);
                        }}
                      />
                    </Tooltip>
                  </Space>
                )}
              </div>
            </Radio>
          ))}
        </Space>
      </Radio.Group>

      <Modal
        title={editingPreset ? '编辑预设' : '创建自定义预设'}
        open={isModalVisible}
        onOk={handleSavePreset}
        onCancel={() => setIsModalVisible(false)}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            temperature: 0.7,
            topP: 0.85,
            maxTokens: 1500,
            presencePenalty: 0,
            frequencyPenalty: 0
          }}
        >
          <Form.Item
            label="预设名称"
            name="name"
            rules={[{ required: true, message: '请输入预设名称' }]}
          >
            <Input placeholder="例如：技术文档" />
          </Form.Item>
          
          <Form.Item
            label="描述"
            name="description"
            rules={[{ required: true, message: '请输入描述' }]}
          >
            <Input placeholder="例如：适合编写技术文档和API说明" />
          </Form.Item>
          
          <Form.Item
            label="温度 (Temperature)"
            name="temperature"
            rules={[{ required: true }]}
          >
            <Input type="number" min={0} max={1} step={0.1} />
          </Form.Item>
          
          <Form.Item
            label="Top-p"
            name="topP"
            rules={[{ required: true }]}
          >
            <Input type="number" min={0} max={1} step={0.05} />
          </Form.Item>
          
          <Form.Item
            label="最大Token数"
            name="maxTokens"
            rules={[{ required: true }]}
          >
            <Input type="number" min={100} max={8192} step={100} />
          </Form.Item>
          
          <Form.Item
            label="存在惩罚 (Presence Penalty)"
            name="presencePenalty"
          >
            <Input type="number" min={-2} max={2} step={0.1} />
          </Form.Item>
          
          <Form.Item
            label="频率惩罚 (Frequency Penalty)"
            name="frequencyPenalty"
          >
            <Input type="number" min={-2} max={2} step={0.1} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default PresetSelector;